# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
from DoubanBook.spiders import proxy89ip
from DoubanBook.modules import proxyip
from DoubanBook.settings import USER_AGENT_LIST
from DoubanBook.common.redis_opt import RedisOpt,RedisConstant
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
import random

class DoubanbookSpiderMiddleware(object):



    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.

        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class DoubanbookDownloaderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        spider.logger.info('======================DoubanbookSpiderMiddleware=====================')
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class ProxySettingMiddleware(object):
    def spider_opened(self,spider):
        if 'proxy89ip' == spider.name:
            self.redisOpt.s_set(RedisConstant.PROXY_IP_89_RUN_STATUS, '1', 1800)

        spider.logger.info('Spider opened: %s' % spider.name)
        pass

    def process_request(self, request, spider):
        redisOpt = RedisOpt.get_instance()
        spider.logger.info('ProxySettingMiddleware redisOpt>>>{}'.format(redisOpt))

        if '0' == redisOpt.s_get(key = RedisConstant.JIAYUAN_PORXY_STATUS) and 'proxy89ip' != spider.name:
            spider.logger.info('检测到代理更换信息')
            if redisOpt.l_len(name = RedisConstant.PROXY_IP_89_LIST_KEY) > 0:
                proxy = redisOpt.l_rpop(name = RedisConstant.PROXY_IP_89_LIST_KEY)
                if isinstance(proxy, bytes):
                    proxy = bytes.decode(proxy)

                if len(proxy.strip(':')) == 2 and not(proxyip.check_proxy_effect(proxy.strip(':')[0],proxy.strip(':')[1],60)):
                    return

                request.meta['proxy'] = 'http://{}'.format(proxy)
                spider.logger.info('代理替换>>>{}'.format(proxy))
                redisOpt.s_set(key=RedisConstant.JIAYUAN_PORXY_STATUS,value = '1',expire = 1800)
            else:
                spider.logger.info('==============爬取代理IP=============')

                if '1' != redisOpt.s_get(RedisConstant.PROXY_IP_89_RUN_STATUS) and 'proxy89ip' != spider.name:
                    process = CrawlerProcess(settings = get_project_settings())
                    process.crawl('jiayuan')
                    process.stop()
                    process.crawl('proxy89ip')
                    process.start()

    pass

class UserAgentRandomMiddleware(object):

    def spider_opened(self,spider):
        if 'proxy89ip' == spider.name:
            self.redisOpt.s_set(RedisConstant.PROXY_IP_89_RUN_STATUS, '1', 1800)

        spider.logger.info('Spider opened: %s' % spider.name)
        pass

    def process_request(self,request,spider):
        if 'jiayuan_user_list' == spider.name:
            request.headers.setdefault('User-Agent', random.choice(USER_AGENT_LIST))
            spider.logger.info('request.headers>>{}'.format(request.headers))
            pass
        #request.headers.setdefault('User-Agent', random.choice(USER_AGENT_LIST))
        #request.headers.setdefault()
        #spider.logger.info('request.headers>>{}'.format(request.headers))
